<template>
  <el-dialog title="选择商品" :visible.sync="visible" width="1100px" append-to-body
    class="goods-selector-dialog" :close-on-click-modal="false">
    <div class="app-container">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--货品类别数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="categoryName" placeholder="请输入类别名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" @input="filterNode" />
            </div>
            <div class="head-container">
              <el-tree :data="categoryOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--货品数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="货品代码" prop="goodsCode">
                <el-input
                  v-model="queryParams.goodsCode"
                  placeholder="请输入货品代码"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="品名规格" prop="goodsSpec">
                <el-input
                  v-model="queryParams.goodsSpec"
                  placeholder="请输入品名规格"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <!-- <el-form-item label="供应商品名" prop="supplyGoodsName">
                <el-input
                  v-model="queryParams.supplyGoodsName"
                  placeholder="请输入供应商品名"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item> -->
              <!-- <el-form-item label="货品类别ID" prop="goodsCategoryId">
                <el-input
                  v-model="queryParams.goodsCategoryId"
                  placeholder="请输入货品类别ID"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item> -->
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['business:goods:add']"
                >新增</el-button>
              </el-col>
            </el-row>

            <el-table 
              ref="table"
              v-loading="loading" 
              :data="goodsList" 
              @selection-change="handleSelectionChange"
              height="450"
              :row-key="row => row.id">
              <el-table-column 
                type="selection" 
                width="55" 
                align="center"
                :reserve-selection="true" />
              <el-table-column label="数量" align="center" width="140">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.quantity"  :max="9999" size="mini" @change="handleQuantityChange(scope.row)"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="货品代码" align="center" prop="goodsCode" />
              
              <el-table-column label="货品图片" align="center" prop="goodsImage" width="100">
                <template slot-scope="scope">
                  <el-image 
                    v-if="scope.row.goodsImage" 
                    :src="getImageUrl(scope.row.goodsImage)" 
                    style="width: 60px; height: 60px;"
                    :preview-src-list="[getImageUrl(scope.row.goodsImage)]">
                  </el-image>
                  <div v-else class="image-placeholder">
                    <i class="el-icon-picture-outline"></i>
                    <span>暂无图片</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="品名规格" align="center" prop="goodsSpec" :show-overflow-tooltip="true" />
              <!-- <el-table-column label="供应商品名" align="center" prop="supplyGoodsName" :show-overflow-tooltip="true" /> -->
              <!-- <el-table-column label="货品类别" align="center" prop="goodsCategoryName" /> -->
              <el-table-column label="主计量单位" align="center" prop="primaryUnit" />
              <!-- <el-table-column label="换算率" align="center" prop="conversionRate" /> -->
              <el-table-column label="库存数量" align="center" prop="stockQuantity" />
              
              <el-table-column label="单价" align="center" width="140">
                <template slot-scope="scope">
                  <el-input-number 
                    v-model="scope.row.unitPrice" 
                    :precision="2" 
                    :step="0.1" 
                    :min="0" 
                    size="mini" 
                    @change="handlePriceChange(scope.row)">
                  </el-input-number>
                </template>
              </el-table-column>
            </el-table>
            
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </pane>
      </splitpanes>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </div>

    <!-- 添加或修改货品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="货品代码" prop="goodsCode">
          <el-input v-model="form.goodsCode" placeholder="请输入货品代码" />
        </el-form-item>
        <el-form-item label="品名规格" prop="goodsSpec">
          <el-input v-model="form.goodsSpec" placeholder="请输入品名规格" />
        </el-form-item>
        <el-form-item label="供应商品名" prop="supplyGoodsName">
          <el-input v-model="form.supplyGoodsName" placeholder="请输入供应商品名" />
        </el-form-item>
        <el-form-item label="货品类别" prop="goodsCategoryId">
          <treeselect
            v-model="form.goodsCategoryId"
            :options="categoryOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="请选择货品类别"
          />
        </el-form-item>
        <el-form-item label="主计量单位" prop="primaryUnit">
          <el-input v-model="form.primaryUnit" placeholder="请输入主计量单位" />
        </el-form-item>
        <el-form-item label="辅助单位" prop="secondaryUnit">
          <el-input v-model="form.secondaryUnit" placeholder="请输入辅助单位" />
        </el-form-item>
        <el-form-item label="换算率" prop="conversionRate">
          <el-input v-model="form.conversionRate" placeholder="请输入换算率" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stockQuantity">
          <el-input v-model="form.stockQuantity" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="期初成本" prop="initialCost">
          <el-input v-model="form.initialCost" placeholder="请输入期初成本" />
        </el-form-item>
        <el-form-item label="进货价" prop="purchasePrice">
          <el-input v-model="form.purchasePrice" placeholder="请输入进货价" />
        </el-form-item>
        <el-form-item label="零售价" prop="retailPrice">
          <el-input v-model="form.retailPrice" placeholder="请输入零售价" />
        </el-form-item>
        <el-form-item label="批发价1" prop="wholesalePrice1">
          <el-input v-model="form.wholesalePrice1" placeholder="请输入批发价1" />
        </el-form-item>
        <el-form-item label="批发价2" prop="wholesalePrice2">
          <el-input v-model="form.wholesalePrice2" placeholder="请输入批发价2" />
        </el-form-item>
        <el-form-item label="最高库存" prop="maxStock">
          <el-input v-model="form.maxStock" placeholder="请输入最高库存" />
        </el-form-item>
        <el-form-item label="最低库存" prop="minStock">
          <el-input v-model="form.minStock" placeholder="请输入最低库存" />
        </el-form-item>
        <el-form-item label="货品图片" prop="goodsImage">
          <image-upload
            v-model="form.goodsImage"
            :limit="3"
            :fileSize="2"
            :fileType="['jpg', 'jpeg', 'png']"
            :isShowTip="true"
            class="compact-upload"
          />
          <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods, listCategory, importGoods } from "@/api/business/goods";
import { getGoodsListByReceiptCode } from "@/api/business/receipt";
import { getToken } from "@/utils/auth";
import { getImageUrl } from "@/utils/image";
import { Splitpanes, Pane } from "splitpanes";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import "splitpanes/dist/splitpanes.css";

export default {
  name: "GoodsSelector",
  components: { Splitpanes, Pane, Treeselect },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    selectedGoods: {
      type: Array,
      default: () => []
    },
    activeRowIndex: {
      type: Number,
      default: -1
    },
    receiptCode: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      goodsList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsCode: null,
        goodsSpec: null,
        supplyGoodsName: null,
        goodsCategoryId: null,
        primaryUnit: null,
        secondaryUnit: null,
        conversionRate: null,
        stockQuantity: null,
        initialCost: null,
        purchasePrice: null,
        retailPrice: null,
        wholesalePrice1: null,
        wholesalePrice2: null,
        maxStock: null,
        minStock: null,
      },
      form: {
        id: null,
        goodsCode: null,
        goodsSpec: null,
        supplyGoodsName: null,
        goodsCategoryId: null,
        primaryUnit: null,
        secondaryUnit: null,
        conversionRate: null,
        stockQuantity: null,
        initialCost: null,
        purchasePrice: null,
        retailPrice: null,
        wholesalePrice1: null,
        wholesalePrice2: null,
        maxStock: null,
        minStock: null,
        remark: null,
        goodsImage: [],
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      },
      rules: {
        goodsCode: [
          { required: true, message: "货品代码不能为空", trigger: "blur" }
        ],
        goodsSpec: [
          { required: true, message: "品名规格不能为空", trigger: "blur" }
        ],
        goodsCategoryId: [
          { required: true, message: "货品类别不能为空", trigger: "blur" }
        ]
      },
      categoryName: undefined,
      categoryOptions: undefined,
      defaultProps: {
        children: "children",
        label: "categoryName"
      },
      upload: {
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/business/goods/importData",
        imageUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      },
      internalSelectedGoods: [],
      selectedIds: new Set(),
    };
  },
  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      }
    }
  },
  watch: {
    categoryName(val) {
      this.$refs.tree.filter(val);
    },
    visible(newVal) {
      if (newVal) {
        this.clearSelection();
        this.getList();
        
        if (this.selectedGoods && this.selectedGoods.length > 0) {
          this.selectedGoods.forEach(good => {
            this.selectedIds.add(good.id);
            this.internalSelectedGoods.push(good);
          });
          
          this.$nextTick(() => {
            this.selectTableRows();
          });
        }
      }
    },
    selectedGoods: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.selectedIds.clear();
          this.internalSelectedGoods = [...newVal];
          
          newVal.forEach(good => {
            this.selectedIds.add(good.id);
          });
          
          if (this.visible && this.$refs.table) {
            this.selectTableRows();
          }
        }
      },
      immediate: true
    }
  },
  created() {
    this.getList();
    this.getCategoryTree();
  },
  methods: {
    getCategoryTree() {
      listCategory().then(response => {
        this.categoryOptions = this.handleTree(response.data, "id", "parentId");
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.categoryName.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.queryParams.goodsCategoryId = data.id;
      this.handleQuery();
    },
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows.map(item => ({
          ...item,
          quantity: item.quantity || 1,
          unitPrice: item.unitPrice || 0,
          totalPrice: ((item.quantity ) * (item.unitPrice)).toFixed(2)
        }));
        this.total = response.total;
        this.loading = false;
        
        this.$nextTick(() => {
          this.goodsList.forEach(row => {
            if (this.selectedIds.has(row.id)) {
              this.$refs.table.toggleRowSelection(row, true);
            }
          });
        });
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        goodsCode: null,
        goodsSpec: null,
        supplyGoodsName: null,
        goodsCategoryId: null,
        primaryUnit: null,
        secondaryUnit: null,
        conversionRate: null,
        stockQuantity: null,
        initialCost: null,
        purchasePrice: null,
        retailPrice: null,
        wholesalePrice1: null,
        wholesalePrice2: null,
        maxStock: null,
        minStock: null,
        remark: null,
        goodsImage: [],
        delFlag: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.goodsCategoryId = undefined;
      this.$refs.tree && this.$refs.tree.setCurrentKey(null);
      this.selectedIds.clear();
      this.internalSelectedGoods = [];
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.internalSelectedGoods = selection;
      this.selectedIds.clear();
      selection.forEach(row => {
        this.selectedIds.add(row.id);
      });
      this.multiple = selection.length === 0;
    },
    handleSelect(selection, row) {
      if (selection.includes(row)) {
        this.selectedIds.add(row.id);
      } else {
        this.selectedIds.delete(row.id);
      }
      this.updateSelectedGoods();
    },
    handleSelectAll(selection) {
      if (selection.length > 0) {
        selection.forEach(row => {
          this.selectedIds.add(row.id);
        });
      } else {
        this.goodsList.forEach(row => {
          this.selectedIds.delete(row.id);
        });
      }
      this.updateSelectedGoods();
    },
    updateSelectedGoods() {
      this.internalSelectedGoods = this.goodsList.filter(item => this.selectedIds.has(item.id));
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
    handleAdd() {
      this.reset();
      this.getCategoryTree();
      this.open = true;
      this.title = "添加货品信息";
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addGoods(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    importTemplate() {
      this.download('business/goods/importTemplate', {}, `goods_template_${new Date().getTime()}.xlsx`);
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleUploadSuccess(res, file, type) {
      if (res.code === 200) {
        const imageUrl = res.url || process.env.VUE_APP_BASE_API + res.fileName;

        if (!this.form[type]) {
          this.$set(this.form, type, []);
        }

        this.form[type].push({ name: res.fileName, url: imageUrl });
        this.form[type] = [...this.form[type]];
      } else {
        this.$message.error('上传失败：' + res.msg);
      }
    },
    handleRemove(file, fileList, type) {
      this.form[type] = fileList;
    },
    handleQuantityChange(row) {
      console.log("数量变更:", row);
    },
    handlePriceChange(row) {
      row.totalPrice = this.calculateTotalPrice(row);
      console.log("价格变更:", row);
    },
    calculateTotalPrice(row) {
      const quantity = parseFloat(row.quantity) || 0;
      const unitPrice = parseFloat(row.unitPrice) || 0;
      return (quantity * unitPrice).toFixed(2);
    },
    clearSelection() {
      this.selectedIds.clear();
      this.internalSelectedGoods = [];
      this.$refs.table && this.$refs.table.clearSelection();
    },
    handleCancel() {
      this.clearSelection();
      this.visible = false;
      this.$emit('cancel');
    },
    handleConfirm() {
      if (this.selectedIds.size === 0) {
        this.$message.warning("请至少选择一个商品");
        return;
      }
      const selectedGoodsWithQuantity = this.internalSelectedGoods.map(good => ({
        ...good,
        quantity: good.quantity || 1,
        unitPrice: good.unitPrice,
        totalPrice: ((good.quantity) * (good.unitPrice)).toFixed(2)
      }));
      this.$emit('confirm', selectedGoodsWithQuantity);
      this.visible = false;
    },
    selectTableRows() {
      this.$nextTick(() => {
        if (this.$refs.table) {
          this.goodsList.forEach(row => {
            if (this.selectedIds.has(row.id)) {
              this.$refs.table.toggleRowSelection(row, true);
            }
          });
        }
      });
    },
    getImageUrl
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

/* 保留占位符样式 */
.image-placeholder {
  width: 60px;
  height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  margin: 0 auto;
}
</style>
